$( function(){
	init_map();
	tinyMCE.init({theme : "advanced", mode : "exact",elements : "something"});
	init_timezone();
	init_calendar();
	init_fileupload();
	init_price();
	init_form_validation();
	$('#create_btn').click(submit);
	init_repeat();
	maxwidth = 600;
	maxheight = 50;
	$('[name="category"]').change(function(){explode_subcategories($(this));});
	init_tickets();
	init_event_virtual_real_option();
});

function init_timezone(){
	if($('#timezone').val() == ''){
		var timezone = jstz.determine();
		$('#timezone').val(timezone.name());
		recalculate_TimeZone_Offset();
	}
	$('#timezone').change(function(){recalculate_TimeZone_Offset()});
	$('#timezone_container').modalpop({target:'#form',action:function(){$('#timezone_container').modalpop('close')}});
	$('#edit_timezone').click(function(){$('#timezone_container').modalpop('open');})
}

function init_event_virtual_real_option(){
	event_virtual_real_option_change();
	$('[name="virtual"]').change(event_virtual_real_option_change);
	$('#virtual_event_option span').click(function(){$(this).find('input').attr('checked',true); $(this).find('input').change()});
}

function event_virtual_real_option_change(){
	if($('[name="virtual"]:checked').val()==0){
		$('#virtual_event').fadeOut(function(){$('.real_event').fadeIn();});
	}else{
		$('.real_event').fadeOut(function(){$('#virtual_event').fadeIn();});
	}
}

function init_tickets(){
	$('#open_when_publish').disable({target:'#open_before',toggle:function(){ return ($('#open_when_publish').attr('checked'));}});
	$('#sales_setup_container').modalpop({target:'#form', action:function(){$('#sales_setup_container').modalpop('close')}});
	$('#event_payment_option_container span').click(function(){$(this).find('input').attr('checked',true); $(this).find('input').change()});
	$('[name="saleSetup.tickets[0].price"]').keyup(function(){calculate_tax_and_total($(this).val(),$(this).parent().parent())});
	$('[name="saleSetup.tickets[0].amount"]').keyup(function(){calculate_event_capacity()});
	$('#addTicket').click(add_ticket);
	$('[name="saleSetup.feeOption"]').change(recalcuate_tax);
	$('#fee_option_container span').click(function(){$(this).find('input').attr('checked',true); $(this).find('input').change()});
	$('#salesSetup').click(function(){$('#sales_setup_container').modalpop('open');})
}

function recalcuate_tax(){
	$('[name^="ticket.value"]').each(function(){calculate_tax_and_total($(this).val(),$(this).parent().parent())});
}

function add_ticket(){
	var index =$('tr[index]').size();
	var tr = $('<tr index="'+index+'">');
	var td = $( '<td><input name="saleSetup.tickets['+index+'].name" patron=".{0,50}" /></td>'+
				'<td><input name="saleSetup.tickets['+index+'].price" patron="\\d{0,5}\\.{0,1}\\d{0,2}" default="0.00"  value="0.00" /></td>'+
				'<td name="tax"></td>'+
				'<td name="total"></td>'+
				'<td><input name="saleSetup.tickets['+index+'].amount" type="numeric" patron="\\d{0,5}" default="0"/></td>'+
				'<td><a name="delete">x</a></td>');
	init_inputs(td);
	tr.append(td);
	td.find('[name="saleSetup.tickets['+index+'].price"]').keyup(function(){calculate_tax_and_total($(this).val(),$(this).parent().parent())});
	td.find('[name="saleSetup.tickets['+index+'].amount"]').keyup(function(){calculate_event_capacity()});
	td.find('[name="delete"]').click(function(){remove_ticket($(this).parent().parent())});
	$('#table_tickets').append(tr);
}

function remove_ticket(row){
	var index = parseInt(row.attr('index'));
	row.fadeOut(function(){
		$(this).remove();
		$('tr[index]:gt('+(index-1)+')').each(function(i){change_names(index,i,$(this))})
	}); 
	
}

function change_names(index,offset,row){
	//alert(row.attr('index'));
	row.attr("index",(index+offset));
	row.find('[name$=".price"]').attr('name',"saleSetup.tickets["+(index+offset)+"]");
	row.find('[name$=".amount"]').attr('name',"saleSetup.tickets["+(index+offset)+"]");
	row.find('[name$=".name"]').attr('name',"saleSetup.tickets["+(index+offset)+"]");
	
}

function calculate_tax_and_total(ticketVal,row){
	var ticketVal = parseFloat(ticketVal);
	var tax = $('[name="saleSetup.feeOption"]:checked').val()==1? parseFloat((ticketVal * 0.9).toFixed(2)): 0.00;
	row.find('td[name="tax"]').text(tax)
	row.find('td[name="total"]').text((tax + ticketVal).toFixed(2));
}

function calculate_event_capacity(){
	var capacity = 0;
	var partial_capacity;
	$('#table_tickets [name^="saleSetup.tickets.amount"]').each(
			function(){
				partial_capacity = parseInt($(this).val());
				capacity +=parseInt(partial_capacity);
			});
}

function init_repeat(){
	$('#repeat_daily_box').modalpop({action:repeat_daily});
	$('#repeat_weekly_box').modalpop({action:repeat_weekly});
	$('#repeat_monthly_box').modalpop({action:repeat_monthly});
	$('#repeat').change(repeat_dialog);
}

function repeat_dialog(){
	var repeat = parseInt($('#repeat').val());
	switch (repeat) {
		case 0:
			//$('#repeat_dates').html('');
			break;
	
		case 1:
			$('#repeat_daily_box').modalpop('open');
			break;
		case 2:
			$('#repeat_weekly_box').modalpop('open');
			break;
		case 3:
			$('#repeat_monthly_box').modalpop('open');
			break;

	}
}

function change_repeat(){
	var repeat = parseInt($('#repeat').val());
	switch (repeat) {
		case 0:
			break;
		case 1:
			repeat_daily();
			break;
		case 2:
			repeat_weekly();
			break;
		case 3:
			repeat_monthly();
			break;

	}
}

function repeat_daily(){
	var url = PrivateUrls['REPEAT_DAILY'];
	$.ajax({
	    url: url,
	    data: {
	    	'timerange.startDay':parseInt($('[name="days[0].startDay"]').val()),
	    	'timerange.endDay':parseInt($('[name="days[0].endDay"]').val()),
	    	'timerange.startHour':parseInt($('[name="days[0].startHour"]').val()),
	    	'timerange.endHour':parseInt($('[name="days[0].endHour"]').val()),
	    	'timerange.startMinute':parseInt($('[name="days[0].startMinute"]').val()),
	    	'timerange.endMinute':parseInt($('[name="days[0].endMinute"]').val()),
	    	frecuency:parseInt($('#daily_repeat_frecuency').val()),
	    	endDateTime:parseInt(timezone_time($('#daily_repeat_last_date').datepicker( "getDate" ))),
	    	'timezoneId':$('#timezone').val()
	    },
	    success: function(response){
	    	$('#repeat_daily_box').modalpop('close');
	    	$('#repeat_dates').html(response);
	    },
		dataType:"html"
	});
}

function repeat_weekly(){
	var url = PrivateUrls['REPEAT_WEEKLY'];
	var days= new Array();
	
	$('[name=weekly_repeat_day]:checked').each(
		function(){days.push(parseInt($(this).val()));} 
	);
	$.ajax({
	    url: url,
	    data: {
	    	'timerange.startDay':parseInt($('[name="days[0].startDay"]').val()),
	    	'timerange.endDay':parseInt($('[name="days[0].endDay"]').val()),
	    	'timerange.startHour':parseInt($('[name="days[0].startHour"]').val()),
	    	'timerange.endHour':parseInt($('[name="days[0].endHour"]').val()),
	    	'timerange.startMinute':parseInt($('[name="days[0].startMinute"]').val()),
	    	'timerange.endMinute':parseInt($('[name="days[0].endMinute"]').val()),
	    	endDateTime:parseInt(timezone_time($('#weekly_repeat_end_date').datepicker( "getDate" ))),
	    	daysOfWeek:JSON.stringify(days),
	    	frecuency:parseInt($('#weekly_repeat_frecuency').val()),
	    	'timezoneId':$('#timezone').val()
	    },
	    success: function(response){
	    	$('#repeat_weekly_box').modalpop('close');
	    	$('#repeat_dates').html(response);	    	
		},
		dataType:"html"
	});
}

function repeat_monthly(){
	var url = PrivateUrls['REPEAT_MONTHLY'];
	$.ajax({
	    url: url,
	    data: {
	    	'timerange.startDay':parseInt($('[name="days[0].startDay"]').val()),
	    	'timerange.endDay':parseInt($('[name="days[0].endDay"]').val()),
	    	'timerange.startHour':parseInt($('[name="days[0].startHour"]').val()),
	    	'timerange.endHour':parseInt($('[name="days[0].endHour"]').val()),
	    	'timerange.startMinute':parseInt($('[name="days[0].startMinute"]').val()),
	    	'timerange.endMinute':parseInt($('[name="days[0].endMinute"]').val()),
	    	 repeatDay:parseInt($('#monthly_repeat_day').val()),
	    	 repeatDayOrder:parseInt($('#monthly_repeat_order').val()),
	    	 repeatFrecuency:parseInt($('#monthly_repeat_frecuency').val()),
	    	 endDateTime: parseInt(timezone_time($('#monthly_repeat_end_date').datepicker( "getDate" ))),
	    	 'timezoneId':$('#timezone').val()
	    },
	    success: function(response){
	    	$('#repeat_monthly_box').modalpop('close');
	    	$('#repeat_dates').html(response);	   
	    },
		dataType:"html"
	});
}

function init_form_validation(){
	$("#form").validate({
		invalidHandler: function(form, validator){},
		rules:{
			'title':{
				required:true,
				maxlength:255
			},
			'subtitle':{
				maxlength:255
			},
			'place.address':{
				required:true,
				maxlength:255
			},
			'date':{
				required:true
			},
			'hour':{
				required:true
			},
			'description':{
				maxlength:255				
			},
			'organizer':{
				required: true
			},
			'email':{
				email:true
			},
			'category':{
				required: true
			}
			
	}}); 
}

function init_map(){
	
	$('#map').gmap();
	var input = document.getElementById('address');
	var options = {	types: ['geocode'],};
	autocomplete = new google.maps.places.Autocomplete(input, options);
	google.maps.event.addListener(autocomplete, 'place_changed', function() {
		 var place = autocomplete.getPlace();
		 load_address(place);
	 });

	if($('#lat').val() != ""  && $('#lat').val() != undefined && $('#lng').val()!= undefined && $('#lng').val()!= "")
		$('#map').gmap('addMarker',{markerOptions:{location:new google.maps.LatLng(parseFloat($('#lat').val()),parseFloat($('#lng').val()))},clearMap:true});
}

function init_calendar(){
	
	if($('[name="days[0].startDay"]').val() != '0'){
		$("#dayFrom_0").datepicker("setDate", new Date(parseInt($('[name="days[0].startDay"]').val())));
	}else{
		var dateFrom = new Date();
		$("#dayFrom_0").datepicker("setDate", dateFrom);
		$('[name="days[0].startDay"]').val(timezone_time(dateFrom));
	}
	
	if($('[name="days[0].endDay"]').val() != '0'){
		$("#dayTo_0").datepicker("setDate", new Date(parseInt($('[name="days[0].endDay"]').val())));
	}else{
		$("#dayTo_0").datepicker("setDate", new Date(parseInt($('[name="days[0].startDay"]').val())));
	}
	
	$('#dayFrom_0').change(
			function(){
				var dateFrom = parseInt(timezone_time($("#dayFrom_0").datepicker("getDate")));
				var dateTo = parseInt(timezone_time($("#dayTo_0").datepicker("getDate")));
				
				$('[name="days[0].startDay"]').val(dateFrom);

				if(dateFrom >= dateTo ){
					$("#dayTo_0").datepicker("setDate", $('#dayFrom_0').datepicker("getDate"));
					$("#dayTo_0").change();
				}else{
					repeat_dialog();
				}
				
				$("#dayTo_0").datepicker('option','minDate',$('#dayFrom_0').datepicker("getDate"));
			});
	
	$('#dayTo_0').change(
			function(){
				$('[name="days[0].endDay"]').val(timezone_time($("#dayTo_0").datepicker("getDate")));
				repeat_dialog();
			});

	
	
	$("#calendar_img").click(function(){$("#dayFrom_0").focus()});
	$("#calendar_img_to").click(function(){$("#dayTo_0").focus()});
}

function init_fileupload(){
	$('#flyer_label').image_uploader({target_selector:'#flyer_label',input_name:'flyer',img_src:img_url});
}

function init_price(){
	event_type_change();
	$('#free_event').hide();
	$('#paid_event').hide();
	$('[name="free"]').change(event_type_change);
}

function event_type_change(){
	if($('[name="free"]:checked').val()==1){
		free_event();
	
	}else{
		paid_event();
	}
}

function paid_event(){
	$('#free_event').fadeOut(function(){$('#paid_event').fadeIn();});
}

function free_event(){
	$('#paid_event').fadeOut(function(){$('#free_event').fadeIn();});
}

 function submit(){
	 $('#form').submit();
 }
 
 
 
 function codeAddress(){
	 google.maps.event.addListener(autocomplete, 'place_changed', function() {
		 var place = autocomplete.getPlace();
		 load_address(place);
	 }); 
 }
 
function load_address(address){
	  delete addresses_results;
	  $('#map').gmap('addMarker',{markerOptions:{position:address.geometry.location},clearMap:true});
	  $('#lat').val(address.geometry.location.lat());
	  $('#lng').val(address.geometry.location.lng());  
 }

function explode_subcategories(category){
	var url = PrivateUrls['GET_SUBCATEGORIES'];
	
	$.ajax({
	    url: url,
	    data: {'categoryId':category.val()},
	    success: function(result){
	    	if(!result.success){
	    		return;
	    	}
	    	
	    	if(result.response != undefined && result.response.length > 0){
	    		create_subcategories(result.response);
	    	}else{
	    		remove_subcategories(category.attr('id'));
	    	}
	    }
	});	    		
	    	
	   
}

function create_subcategories(categories){
	var index = $('[name="category"]').size() + 1;
	var select = $('<select id="'+index+'" name="category">');
	for(var i=0;i<categories.length;i++){
		var option = $('<option value="'+categories[i].id+'">'+categories[i].description+'</option>');
		select.append(option);
	}
	select.change(function(){explode_subcategories($(this));});
	var span = $('<span>>></span>');
	span.append(select);
	span.insertAfter($('[name="category"]:last'));
}

function remove_subcategories(from){
	var categories_combos = $('[name="category"]');
	for(var i=(parseInt(from)+1);i<categories_combos.length;i++){
		$(categories_combos[i]).parent().remove();
	}
}

function recalculate_TimeZone_Offset(){
	var url = PrivateUrls['GET_TIMEZONE_OFFSET'];
	$.ajax({
	    url: url,
	    data: {'timezoneId':$('#timezone').val()},
	    success: function(result){
	    	if(!result.success){
	    		return;
	    	}
	    	
	    	window.timezoneOffset = result.response;
	    	 $('#dayFrom_0').change();
	    }
	});	 
}